<template>
  <view class="work-orders-container">
    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-card total">
        <text class="stat-number">{{ workOrderStats.total }}</text>
        <text class="stat-label">工单总数</text>
      </view>
      <view class="stat-card pending">
        <text class="stat-number">{{ workOrderStats.pending }}</text>
        <text class="stat-label">待处理</text>
      </view>
      <view class="stat-card in-progress">
        <text class="stat-number">{{ workOrderStats.inProgress }}</text>
        <text class="stat-label">处理中</text>
      </view>
      <view class="stat-card completed">
        <text class="stat-number">{{ workOrderStats.completed }}</text>
        <text class="stat-label">已完成</text>
      </view>
    </view>

    <!-- 筛选和搜索 -->
    <view class="filter-section">
      <view class="status-tabs">
        <text
          v-for="tab in statusTabs"
          :key="tab.value"
          class="status-tab"
          :class="{ active: activeStatus === tab.value }"
          @click="activeStatus = tab.value"
        >{{ tab.label }}</text>
      </view>

      <view class="search-bar">
        <view class="search-input-wrapper">
          <text class="search-icon">🔍</text>
          <input
            v-model="searchKeyword"
            placeholder="搜索工单编号或设备"
            class="search-input"
            @input="handleSearch"
          />
        </view>
        <view class="filter-btn" @click="showAdvancedFilter = !showAdvancedFilter">
          <text class="filter-icon">⚙️</text>
          <text>筛选</text>
        </view>
      </view>

      <!-- 高级筛选 -->
      <view class="advanced-filter" v-if="showAdvancedFilter">
        <view class="filter-row">
          <text class="filter-label">优先级：</text>
          <view class="filter-options">
            <text
              v-for="priority in priorityOptions"
              :key="priority.value"
              class="filter-option"
              :class="{ active: filterPriority === priority.value }"
              @click="filterPriority = priority.value"
            >{{ priority.label }}</text>
          </view>
        </view>
        <view class="filter-row">
          <text class="filter-label">时间范围：</text>
          <view class="filter-options">
            <text
              v-for="time in timeRangeOptions"
              :key="time.value"
              class="filter-option"
              :class="{ active: filterTimeRange === time.value }"
              @click="filterTimeRange = time.value"
            >{{ time.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 工单列表 -->
    <view class="work-order-list">
      <view
        v-for="order in filteredWorkOrders"
        :key="order.id"
        class="work-order-card"
        @click="goToWorkOrderDetail(order.id)"
      >
        <!-- 工单头部 -->
        <view class="order-header">
          <view class="order-title">
            <text class="order-id">#{{ order.id }}</text>
            <text class="order-type">{{ order.type }}</text>
          </view>
          <view class="order-status"
            :class="getStatusClass(order.status)"
          >
            {{ getStatusText(order.status) }}
          </view>
        </view>

        <!-- 工单内容 -->
        <view class="order-content">
          <text class="order-desc">{{ order.description }}</text>
          <view class="order-device">
            <text class="device-icon">🏠</text>
            <text class="device-name">{{ order.deviceName }}</text>
            <text class="device-location">📍{{ order.deviceLocation }}</text>
          </view>
        </view>

        <!-- 工单信息 -->
        <view class="order-info">
          <view class="info-item priority">
            <text class="info-label">优先级：</text>
            <view class="priority-badge" :class="order.priority"></view>
            <text class="priority-text">{{ getPriorityText(order.priority) }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">创建时间：</text>
            <text class="info-value">{{ order.createTime }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">负责人：</text>
            <text class="info-value">{{ order.assignee || '未分配' }}</text>
          </view>
        </view>

        <!-- 工单进度 -->
        <view class="order-progress">
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: getProgressWidth(order.status) + '%' }"></view>
          </view>
          <text class="progress-text">{{ getProgressText(order.status) }}</text>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredWorkOrders.length === 0" class="empty-state">
      <text class="empty-icon">📋</text>
      <text class="empty-text">暂无工单数据</text>
      <text class="empty-desc">{{ getEmptyDesc() }}</text>
    </view>

    <!-- 创建工单悬浮按钮 -->
    <view class="fab" @click="createWorkOrder">
      <text class="fab-icon">➕</text>
    </view>

    <!-- 自定义底部导航 -->
    <SimpleTabNav :currentTab="2" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onPullDownRefresh, onLoad } from '@dcloudio/uni-app'
import SimpleTabNav from '@/components/SimpleTabNav.vue'

// 搜索关键词
const searchKeyword = ref('')

// 筛选状态
const activeStatus = ref('all')
const showAdvancedFilter = ref(false)
const filterPriority = ref('all')
const filterTimeRange = ref('all')

// 状态标签
const statusTabs = ref([
  { label: '全部', value: 'all' },
  { label: '待处理', value: 'pending' },
  { label: '处理中', value: 'in_progress' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
])

// 优先级选项
const priorityOptions = ref([
  { label: '全部', value: 'all' },
  { label: '紧急', value: 'urgent' },
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
])

// 时间范围选项
const timeRangeOptions = ref([
  { label: '全部', value: 'all' },
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' }
])

// 模拟工单数据
const workOrders = ref([
  {
    id: 'WO-20240115001',
    type: '设备维护',
    description: '移动厕所-001需要定期清洁和维护，检查洗手液和纸巾余量',
    deviceName: '移动厕所-001',
    deviceLocation: '人民广场东侧',
    status: 'pending',
    priority: 'medium',
    createTime: '2024-01-15 09:30',
    assignee: '张师傅',
    estimatedTime: '2小时'
  },
  {
    id: 'WO-20240115002',
    type: '故障维修',
    description: '移动厕所-002门锁故障，无法正常开启，需要紧急维修',
    deviceName: '移动厕所-002',
    deviceLocation: '中央公园南门',
    status: 'in_progress',
    priority: 'urgent',
    createTime: '2024-01-15 10:15',
    assignee: '李师傅',
    estimatedTime: '1小时'
  },
  {
    id: 'WO-20240115003',
    type: '日常巡检',
    description: '对商业街区域的移动厕所进行日常巡检和设备状态检查',
    deviceName: '移动厕所-003',
    deviceLocation: '商业街北口',
    status: 'completed',
    priority: 'low',
    createTime: '2024-01-15 08:00',
    assignee: '王师傅',
    estimatedTime: '30分钟'
  },
  {
    id: 'WO-20240115004',
    type: '清洁服务',
    description: '移动厕所-004需要深度清洁，包括地面、墙面和设备的全面清洁',
    deviceName: '移动厕所-004',
    deviceLocation: '体育馆西门',
    status: 'pending',
    priority: 'high',
    createTime: '2024-01-15 14:20',
    assignee: null,
    estimatedTime: '1.5小时'
  },
  {
    id: 'WO-20240115005',
    type: '设备更换',
    description: '移动厕所-005的洗手液分配器损坏，需要更换新的设备',
    deviceName: '移动厕所-005',
    deviceLocation: '医院东门',
    status: 'cancelled',
    priority: 'medium',
    createTime: '2024-01-15 11:45',
    assignee: '赵师傅',
    estimatedTime: '45分钟'
  }
])

// 工单统计
const workOrderStats = computed(() => {
  const total = workOrders.value.length
  const pending = workOrders.value.filter(o => o.status === 'pending').length
  const inProgress = workOrders.value.filter(o => o.status === 'in_progress').length
  const completed = workOrders.value.filter(o => o.status === 'completed').length
  return { total, pending, inProgress, completed }
})

// 筛选后的工单列表
const filteredWorkOrders = computed(() => {
  let result = workOrders.value

  // 状态筛选
  if (activeStatus.value !== 'all') {
    result = result.filter(order => order.status === activeStatus.value)
  }

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(order =>
      order.id.toLowerCase().includes(keyword) ||
      order.description.toLowerCase().includes(keyword) ||
      order.deviceName.toLowerCase().includes(keyword) ||
      order.deviceLocation.toLowerCase().includes(keyword)
    )
  }

  // 优先级筛选
  if (filterPriority.value !== 'all') {
    result = result.filter(order => order.priority === filterPriority.value)
  }

  // 时间范围筛选 (简化处理)
  if (filterTimeRange.value !== 'all') {
    // 这里可以根据实际需求添加时间筛选逻辑
    console.log('时间范围筛选:', filterTimeRange.value)
  }

  return result
})

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过 computed 自动处理
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'status-pending',
    in_progress: 'status-in-progress',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    urgent: '紧急',
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || '未知'
}

// 获取进度宽度
const getProgressWidth = (status: string) => {
  const progressMap: Record<string, number> = {
    pending: 25,
    in_progress: 65,
    completed: 100,
    cancelled: 0
  }
  return progressMap[status] || 25
}

// 获取进度文本
const getProgressText = (status: string) => {
  const progressMap: Record<string, string> = {
    pending: '等待处理',
    in_progress: '正在处理',
    completed: '已完成',
    cancelled: '已取消'
  }
  return progressMap[status] || '未知状态'
}

// 获取空状态描述
const getEmptyDesc = () => {
  if (searchKeyword.value) {
    return '没有找到匹配的工单，请尝试其他关键词'
  } else if (activeStatus.value !== 'all') {
    return '当前状态下暂无工单'
  } else {
    return '当前暂无工单数据，可以创建新的工单'
  }
}

// 跳转到工单详情
const goToWorkOrderDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/work-orders/detail?id=${id}`
  })
}

// 创建工单
const createWorkOrder = () => {
  uni.navigateTo({
    url: '/pages/work-orders/create'
  })
}

// 下拉刷新
onPullDownRefresh(() => {
  // 模拟数据刷新
  setTimeout(() => {
    uni.stopPullDownRefresh()
    uni.showToast({
      title: '刷新成功',
      icon: 'success'
    })
  }, 1000)
})

// 页面加载
onLoad(() => {
  console.log('工单管理页面加载')
})

// 页面挂载
onMounted(() => {
  console.log('工单管理页面初始化')
})
</script>

<style lang="scss" scoped>
.work-orders-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  padding-bottom: 120rpx;
}

// 统计信息
.stats-section {
  display: flex;
  justify-content: space-around;
  padding: 32rpx;
  margin: 24rpx 32rpx 0;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .stat-card {
    text-align: center;
    flex: 1;
    padding: 24rpx 12rpx;
    border-radius: 16rpx;
    transition: all 0.3s ease;

    &.total {
      background: linear-gradient(135deg, #52c41a, #73d13d);
      color: #ffffff;
    }

    &.pending {
      background: linear-gradient(135deg, #faad14, #ffc53d);
      color: #ffffff;
    }

    &.in-progress {
      background: linear-gradient(135deg, #1890ff, #40a9ff);
      color: #ffffff;
    }

    &.completed {
      background: linear-gradient(135deg, #52c41a, #95de64);
      color: #ffffff;
    }

    .stat-number {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      margin-bottom: 8rpx;
    }

    .stat-label {
      display: block;
      font-size: 24rpx;
      opacity: 0.9;
    }
  }
}

// 筛选区域
.filter-section {
  background: #ffffff;
  padding: 24rpx 32rpx;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .status-tabs {
    display: flex;
    gap: 16rpx;
    margin-bottom: 24rpx;
    overflow-x: auto;

    .status-tab {
      padding: 16rpx 32rpx;
      background: #f8f9fa;
      border-radius: 24rpx;
      font-size: 28rpx;
      color: #666;
      white-space: nowrap;
      transition: all 0.3s ease;

      &.active {
        background: linear-gradient(135deg, #52c41a, #73d13d);
        color: #ffffff;
        box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.2);
      }
    }
  }

  .search-bar {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .search-input-wrapper {
      flex: 1;
      position: relative;
      display: flex;
      align-items: center;

      .search-icon {
        position: absolute;
        left: 24rpx;
        font-size: 32rpx;
        color: #999;
      }

      .search-input {
        width: 100%;
        height: 80rpx;
        padding: 0 24rpx 0 80rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 40rpx;
        font-size: 28rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &:focus {
          border-color: #52c41a;
          background: #ffffff;
          box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
        }
      }
    }

    .filter-btn {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 20rpx 24rpx;
      background: linear-gradient(135deg, #52c41a, #73d13d);
      border-radius: 40rpx;
      color: #ffffff;
      font-size: 28rpx;
      font-weight: 500;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

      &:active {
        transform: scale(0.98);
      }
    }
  }

  .advanced-filter {
    margin-top: 24rpx;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 16rpx;

    .filter-row {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .filter-label {
        width: 140rpx;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }

      .filter-options {
        flex: 1;
        display: flex;
        gap: 16rpx;
        flex-wrap: wrap;

        .filter-option {
          padding: 12rpx 24rpx;
          background: #ffffff;
          border: 2rpx solid #e8e8e8;
          border-radius: 24rpx;
          font-size: 26rpx;
          color: #666;
          transition: all 0.3s ease;

          &.active {
            background: linear-gradient(135deg, #52c41a, #73d13d);
            color: #ffffff;
            border-color: #52c41a;
            box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.2);
          }
        }
      }
    }
  }
}

// 工单列表
.work-order-list {
  padding: 0 32rpx;

  .work-order-card {
    background: #ffffff;
    border-radius: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24rpx;

      .order-title {
        flex: 1;

        .order-id {
          display: block;
          font-size: 28rpx;
          color: #52c41a;
          font-weight: bold;
          margin-bottom: 8rpx;
        }

        .order-type {
          display: block;
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }
      }

      .order-status {
        padding: 8rpx 16rpx;
        border-radius: 16rpx;
        font-size: 24rpx;
        font-weight: 500;

        &.status-pending {
          background: #fff7e6;
          color: #faad14;
        }

        &.status-in-progress {
          background: #e6f7ff;
          color: #1890ff;
        }

        &.status-completed {
          background: #f6ffed;
          color: #52c41a;
        }

        &.status-cancelled {
          background: #f5f5f5;
          color: #999;
        }
      }
    }

    .order-content {
      margin-bottom: 24rpx;

      .order-desc {
        display: block;
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 16rpx;
      }

      .order-device {
        display: flex;
        align-items: center;
        gap: 12rpx;
        padding: 16rpx;
        background: #f8f9fa;
        border-radius: 12rpx;

        .device-icon {
          font-size: 28rpx;
        }

        .device-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .device-location {
          font-size: 24rpx;
          color: #666;
        }
      }
    }

    .order-info {
      margin-bottom: 24rpx;

      .info-item {
        display: flex;
        align-items: center;
        padding: 8rpx 0;

        .info-label {
          font-size: 26rpx;
          color: #999;
          margin-right: 12rpx;
        }

        .info-value {
          font-size: 26rpx;
          color: #666;
          font-weight: 500;
        }

        &.priority {
          align-items: center;

          .priority-badge {
            width: 12rpx;
            height: 12rpx;
            border-radius: 50%;
            margin-right: 8rpx;

            &.urgent {
              background: #ff4d4f;
            }

            &.high {
              background: #faad14;
            }

            &.medium {
              background: #1890ff;
            }

            &.low {
              background: #52c41a;
            }
          }

          .priority-text {
            font-size: 26rpx;
            color: #666;
            font-weight: 500;
          }
        }
      }
    }

    .order-progress {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .progress-bar {
        flex: 1;
        height: 8rpx;
        background: #e8e8e8;
        border-radius: 4rpx;
        overflow: hidden;

        .progress-fill {
          height: 100%;
          background: linear-gradient(90deg, #52c41a, #73d13d);
          border-radius: 4rpx;
          transition: width 0.3s ease;
        }
      }

      .progress-text {
        font-size: 24rpx;
        color: #999;
        white-space: nowrap;
      }
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;

  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 24rpx;
    opacity: 0.5;
  }

  .empty-text {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 16rpx;
    font-weight: 500;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
  }
}

// 悬浮按钮
.fab {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #52c41a, #73d13d);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(82, 196, 26, 0.4);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  .fab-icon {
    font-size: 40rpx;
    color: #ffffff;
  }
}
</style>